package com.hay.item.controller;

import com.hay.common.PageResult;
import com.hay.item.pojo.Brand;
import com.hay.item.service.BrandService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @title: BrandController
 * @Author HuangYan
 * @Date: 2020/7/17 22:25
 * @Version 1.0
 */
@Controller
@RequestMapping("brand")
public class BrandController {

    @Autowired
    private BrandService brandService;

    /**
     * 根据查询条件分页并排序查询品牌信息
     * @param key
     * @param page
     * @param rows
     * @param sortBy
     * @param desc
     * @return
     */
    @GetMapping("page")
    public ResponseEntity<PageResult<Brand>> queryBrandsByPage(
            @RequestParam(value = "key", required = false) String key,
            @RequestParam(value = "page", defaultValue = "1") Integer page,
            @RequestParam(value = "rows", defaultValue = "5") Integer rows,
            @RequestParam(value = "sortBy", required = false) String sortBy,
            @RequestParam(value = "desc", required = false) Boolean desc ){
        PageResult<Brand> pageResult = brandService.queryBrandsByPage(key, page, rows, sortBy, desc);
        // 如果查询出来的数据为空，则返回404
        if (CollectionUtils.isEmpty(pageResult.getItems())){
            return ResponseEntity.notFound().build();
        }
        return ResponseEntity.ok(pageResult);
    }

    /**
     * 新增品牌
     * @param brand
     * @param ids
     */
    @PostMapping
    public ResponseEntity<Void> insertBrand(Brand brand, @RequestParam("cids") List<Long> ids){
        brandService.insertBrand(brand, ids);
        return ResponseEntity.status(HttpStatus.CREATED).build();
    }

    /**
     * 删除商品
     * @param bid
     * @return
     */
    @GetMapping("delete/{bid}")
    public ResponseEntity<Void> deleteBrandByBid(@PathVariable("bid") long bid){
        brandService.deleteBrandByBid(bid);
        return ResponseEntity.status(HttpStatus.OK).build();
    }

    /**
     * 根据商品分类cid查询此分类下的商品
     * @param cid
     * @return
     */
    @GetMapping("cid/{cid}")
    public ResponseEntity<List<Brand>> queryBrandListByCid(@PathVariable("cid") long cid){
        List<Brand> list = brandService.queryBrandListByCid(cid);
        if (CollectionUtils.isEmpty(list)){
            return ResponseEntity.notFound().build();
        }
        return ResponseEntity.ok(list);
    }

    /**
     * 根据id查询品牌
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public ResponseEntity<Brand> queryBrandById(@PathVariable("id") Long id){
        Brand brand = brandService.queryBrandById(id);
        if (brand == null){
            ResponseEntity.notFound().build();
        }
        return ResponseEntity.ok(brand);
    }
}
